<template>
<a href="javascript:;" class="list-group-item">
  <span class="indent" v-for="indent in indents" track-by="$index"></span>
  <span v-if="tree.isFolder && !tree.loading" class="icon expand-icon glyphicon" :class="{'glyphicon-plus': !tree.open, 'glyphicon-minus': tree.open}" @click="toggle"></span>
  <span v-if="tree.loading" class="{{ stateIcon}}"></span>
  <span class="{{ customIcon}}"></span>
  {{tree.name}}
  <span class="my-badge" v-show="tree.totalCount > 0">{{tree.totalCount}}</span>
  <button type="button" v-for="action in showActions" class="{{actionClass(action)}}" @click="action.doClick(tree)" :disabled="isActionDisabled(action)">
    {{action.name}}
  </button>
</a>
</template>

<script>
import _ from 'lodash'

export default {
  props: {
    tree: {
      type: Object,
      required: true
    },
    level: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      indents: []
    }
  },
  computed: {
    showActions () {
      return _.filter(this.tree.actions, function(item) {
        return !item.isShow || item.isShow(this.tree)
      }.bind(this))
    },
    stateIcon () {
      if (this.tree.loading) {
        return 'fa fa-spinner fa-spin'
      } else {
        return 'icon glyphicon'
      }
    },
    customIcon () {
      var icon = 'icon node-icon'
      if (this.tree.icon) {
        icon += ' '
        icon += this.tree.icon
      }

      return icon
    }
  },
  methods: {
    isActionDisabled (action) {
      return !(!action.isEnable || action.isEnable(this.tree))
    },
    actionClass (action) {
      return 'btn btn-xs pull-right btn-' + action.type
    },
    toggle () {
      if (this.tree.isFolder) {
        if (this.tree.childs.length === 0) {
          if (!this.tree.open) {
            this.tree.getChilds(this.tree)
          }
        } else {
          this.tree.open = !this.tree.open
        }
      }
    }
  },
  created () {
    for (var i = 0; i < this.level; i++) {
      this.indents.push(1)
    }
  }
}
</script>

<style>
.my-badge {
  display: inline-block;
  min-width: 10px;
  padding: 3px 7px;
  font-size: 12px;
  font-weight: bold;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  background-color: #777;
  border-radius: 10px;
}
.list-group-item > button {
  margin: 1px;
}
</style>